<template>
  <div style="position: relative">
    <el-upload
      ref="upload"
      :action="uploadUrl"
      :headers="headers"
      :with-credentials="true"
      :show-file-list="true"
      :on-success="onSuccess"
      :on-error="onError"
      :on-progress="onProgress"
      :before-upload="beforeUpload"
      :auto-upload="false"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">
        上传到服务器
      </el-button>
      <span class="el-upload__tip">大小不超过10M，文件类型只能为jpg/png/md</span>
    </el-upload>
    <div style="margin-top: 20px">
      <el-upload
        ref="uploadChunk"
        :auto-upload="false"
        :http-request="uploadFile"
        :on-change="handleFileChange"
        :file-list="fileList"
        action="#"
        multiple
      >
        <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
        <el-button
          style="margin-left: 10px"
          v-if="checksum"
          type="success"
          size="small"
          @click="submitUploadChunk"
        >
          上传到服务器
        </el-button>
        <span class="el-upload__tip">大文件切片上传</span>
      </el-upload>
      <el-progress :percentage="percentage" :format="format" v-show="percentage > 0"></el-progress>
    </div>
    <el-color-picker
      v-model="color"
      @change="changeColor"
      style="position: absolute; top: 10px; right: 10px"
    ></el-color-picker>
    <!-- <div class="el-upload__tip" style="margin-top: 30px">
      操作步骤：
      <p>
        1、修改md文件里面的图片地址，地址为：http://refuel.com:8086/refuel/api/minio/getFile?bucketName=mahuaide&objectName=1.jpg
      </p>
      <p>2、将md文件和图片上传到服务器</p>
      <p>
        3、(业务指引)需求人员通知后端开发人员，配置md文件对应的页面，如果一个页面url对应多个md文件，需要分开配置，设置helpId
      </p>
      <p>
        4、(业务指引)后端开发人员通知前端开发人员，在需要引入md文件的页面mounted中调用updateCurrentHelpIdForPage，并根据条件设置helpId
      </p>
      <p>5、测试环境配置与生产环境，md文件中图片地址不同，注意分开文件上传</p>
      <p>6、同名文件会覆盖</p>
      <p>7、打开首页新功能提示开关，首页会弹出最新上传的md文档内容</p>
    </div>
    <el-table :data="tableData" border stripe style="margin-top: 20px">
      <el-table-column
        v-for="col in columns"
        :prop="col.id"
        :key="col.id"
        :label="col.label"
        :width="col.width"
      >
        <template slot-scope="scope">
          <span v-if="col.id === 'uploadDateTime'">
            {{ scope.row.uploadDateTime | timeFormate("YYYY-MM-DD HH:mm:ss") }}
          </span>
          <span v-else-if="col.id === 'switch'">
            <el-switch
              v-if="scope.row.fileName.includes('.md')"
              v-model="scope.row.switch"
              :active-value="1"
              :inactive-value="0"
              @change="changeSwitch(scope.row)"
            >
            </el-switch>
          </span>
          <span v-else>
            {{ scope.row[col.id] }}
          </span>
        </template>
      </el-table-column>
    </el-table> -->
  </div>
</template>

<script>
  import { lsRead } from '@/common/js/ls.js';
  import Worker from '../common/js/checksum.worker.js';
  import axios from 'axios';
  export default {
    name: '',
    props: {},
    components: {},
    data() {
      return {
        color: '',
        percentage: 0,
        fileList: [],
        chunkSize: 1024 * 1024, // 1MB
        currentChunk: 0,
        checksum: '',
        file: null,
        uploadUrl: '',
        headers: {
          Authorization: lsRead('token'),
        },
        columns: [
          { id: 'fileName', label: '文件名称' },
          { id: 'userName', label: '上传人' },
          { id: 'uploadDateTime', label: '上传时间' },
          { id: 'switch', label: '首页新功能', width: '120px' },
        ],
        tableData: [
          {
            fileName: 'kanban-1.png',
            userName: '郑春烨',
            uploadDateTime: 1693271514474,
            switch: 0,
          },
          {
            fileName: 'kanban-2.png',
            userName: '郑春烨',
            uploadDateTime: 1693271514474,
            switch: 0,
          },
          {
            fileName: 'kanban.md',
            userName: '郑春烨',
            uploadDateTime: 1693271514474,
            switch: 0,
          },
          {
            fileName: 'req-1.png',
            userName: '史远芳',
            uploadDateTime: 1693271514474,
            switch: 0,
          },
          {
            fileName: 'req.md',
            userName: '史远芳',
            uploadDateTime: 1693271514474,
            switch: 0,
          },
          {
            fileName: 'index.md',
            userName: '徐薇怡',
            uploadDateTime: 1693271514474,
            switch: 1,
          },
        ],
      };
    },
    computed: {},
    watch: {},
    methods: {
      format() {
        return `${this.percentage}%`;
      },
      handleFileChange(file) {
        this.file = file.raw;
        const worker = new Worker();
        worker.onmessage = event => {
          if (event.data.error) {
            console.error('Error calculating checksum:', event.data.error);
          } else {
            this.checksum = event.data.hash;
          }
          worker.terminate();
        };
        worker.postMessage({
          file: this.file,
          chunkSize: this.chunkSize,
          hashAlgorithm: 'MD5', // or 'SHA256', 'SHA1', etc.
        });
      },
      async uploadFile() {
        const totalChunks = Math.ceil(this.file.size / this.chunkSize);
        for (let i = 0; i < totalChunks; i++) {
          const start = i * this.chunkSize;
          const end = Math.min(start + this.chunkSize, this.file.size);
          const chunk = this.file.slice(start, end);
          const formData = new FormData();
          formData.append('file', chunk);
          formData.append('chunkIndex', i);
          formData.append('totalChunks', totalChunks);
          formData.append('fileName', this.file.name);
          formData.append('checksum', this.checksum);
          await axios.post('/minio/uploadChunk', formData);
          this.percentage = Number((((i + 1) / totalChunks) * 100).toFixed(0));
        }
        this.$message({
          type: 'success',
          message: '上传成功',
        });
        this.checksum = '';
      },
      submitUploadChunk() {
        this.percentage = 0;
        this.$refs.uploadChunk.submit();
      },
      changeSwitch(row) {
        console.log(row);
      },
      onSuccess(response, file, fileList) {
        fileList.forEach((item, index) => {
          if (item.name === file.name) {
            fileList.splice(index, 1);
          }
        });
        this.$message.info(`${file.name}-上传成功`);
      },
      onError(err, file, fileList) {
        this.$message.info(`${file.name}-上传失败`);
      },
      onProgress(event, file, fileList) {},
      beforeUpload(file) {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$message.error('上传文件不能超过 10MB!');
          return isLt10M;
        }
        let lastDot = file.name.lastIndexOf('.');
        let ext = file.name.slice(lastDot, file.name.length + 1);
        if (!['.jpg', '.png', '.md'].includes(ext)) {
          this.$message.error('只能上传jpg/png/md文件');
          return false;
        }
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      changeColor(val) {
        console.log(val);
        this.$store.commit('SETTHEME', {
          key: 'theme',
          value: val,
        });
      },
    },
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {
      this.uploadUrl = axios.defaults.baseURL + '/minio/upload';
      this.color = localStorage.getItem('theme');
    },
    beforeUpdate() {},
    updated() {},
    activated() {},
    deactivated() {},
    beforeDestroy() {},
    destroyed() {},
  };
</script>

<style lang="scss" scoped>
  .el-upload__tip {
    color: var(--color) !important;
    p {
      margin: 5px 0;
    }
  }
</style>
